(function (window, undefined) {
    window.Asc.plugin.init = function (text) {
        var _info = window.Asc.plugin.info;
        var that = this
        var kloud_result_word = ""
        var isGenerating = false
        var controller = new AbortController()

        generateAiWriting()

        window.Asc.plugin.executeMethod("GetSelectedText", [{ Numbering: false }], function (data) {
            if (data === "") {
                alert('empty selected text');
                that.executeCommand('close', '')
            }
            document.getElementById('kloud_selected_text').innerHTML = data
            document.getElementById('kloud_selected_full_text').innerHTML = data

        })

        document.getElementById("kloud_close").onclick = function () {
            that.executeCommand('close', '')
        }

        document.getElementById("kloud_enter").onclick = function () {
            handleEnterPress();
        }

        document.getElementById("kloud_input").addEventListener('keydown', function (event) {
            if (event.key === 'Enter') {
                handleEnterPress();
            }
        });

        document.getElementById("kloud_action_copy").onclick = function () {
            if (document.getElementById("kloud_result").innerHTML && !isGenerating) {
                navigator.clipboard.writeText(document.getElementById("kloud_result").innerHTML);
            }
        }

        document.getElementById("kloud_action_replace").onclick = function () {
            if (document.getElementById("kloud_result").innerHTML && !isGenerating) {
                Asc.scope.text = String(kloud_result_word)
                that.callCommand(function () {
                    var oDocument = Api.GetDocument();
                    var oParagraph = Api.CreateParagraph();
                    oParagraph.AddText(Asc.scope.text); // or oParagraph.AddText(scope.text);
                    oDocument.InsertContent([oParagraph], false, { "KeepTextOnly": true });
                }, true);
            }
        }

        document.getElementById("kloud_action_insert").onclick = function () {
            if (document.getElementById("kloud_result").innerHTML && !isGenerating) {
                Asc.scope.text = String(kloud_result_word)
                window.Asc.plugin.executeMethod("GetSelectedText", [{ Numbering: false }], function (data) {
                    Asc.scope.data = data;
                    that.callCommand(function () {
                        var oDocument = Api.GetDocument();
                        var oParagraph = Api.CreateParagraph();
                        oParagraph.AddText(Asc.scope.data + '\n' + Asc.scope.text); // or oParagraph.AddText(scope.text);
                        oDocument.InsertContent([oParagraph], false, { "KeepTextOnly": true });
                    }, true);
                })
            }
        }

        document.getElementById("kloud_action_try_again").onclick = function () {
            !isGenerating && handleEnterPress()
        }
        document.getElementById("kloud_action_stop").onclick = function () {
            if (isGenerating) {
                isGenerating = false
                controller.abort()
                document.getElementById("kloud_result").innerHTML = ''
                resizeEndStyle()
            }
        }
        document.getElementById('text-action-more').onclick = function () {
            document.getElementById('ellipsis_text_div').style.display = 'none'
            document.getElementById('kloud_selected_full_text').style.display = 'block'
            that.resizeWindow(800, 260, 800, 260, 800, 260);
        }

        function handleEnterPress() {
            if (isGenerating) {
                return
            }
            let user_input = document.getElementById("kloud_input").value
            if (user_input === "") {
                alert('empty input');
                return;
            }
            if (document.querySelector('#kloud_result').value) {
                requestAi(kloud_result_word, user_input)
            } else {
                window.Asc.plugin.executeMethod("GetSelectedText", [{ Numbering: false }], function (data) {
                    if (data === "") {
                        alert('empty selected text');
                        return;
                    }
                    requestAi(data, user_input)
                })
            }

        }

        async function requestAi(data, user_input) {
            resizeStartStyle()
            isGenerating = true

            const { documentTitle } = _info

            const res = await fetch('https://officeapi.kloud.cn/files/getfileInfo?fileName=' + documentTitle, {
                method: 'GET',
            })
            const { data: fileInfo } = await res.json();

            console.log(fileInfo);

            const myHeaders = new Headers();
            myHeaders.append("Content-Type", "application/json");

            const requestOptions = {
                method: "POST",
                headers: myHeaders,
                body: JSON.stringify({
                    attachmentHash: fileInfo.solution_id,
                    brainsId: fileInfo.brains_id,
                    userPrompt: user_input,
                    selectedContent: data,
                    writingType: fileInfo.type == 'meetingSummary' ? 1 : fileInfo.type == 'solution' ? 2 : 3,
                }),
                redirect: "follow",
                dataType: "text/event-stream",
                signal: controller.signal,
            }

            const response = await fetch("https://chatwiseapi.kloud.cn/improve_onlyoffice_data", requestOptions)
            const reader = response.body.getReader()
            const decoder = new TextDecoder()

            document.querySelector('#kloud_result').style.display = ''
            document.querySelector('#kloud_loading').style.display = 'none'
            document.querySelector('#kloud_input').placeholder = 'Ask AI to improve generated text'

            let buffer = ""
            kloud_result_word = ""

            while (true) {
                const { value, done } = await reader.read()
                if (done) {
                    resizeEndStyle()
                    isGenerating = false
                    break
                }
                let chunk = decoder.decode(value)
                let lines = chunk.split('data: ')
                lines.forEach(line => {
                    kloud_result_word += line.replace("\n\n", "")
                    buffer += line.replace("\n\n", "").replace(/\n/g, "<br>")
                })
                handleResult(buffer)
            }
        }

        function resizeStartStyle() {
            that.resizeWindow(800, 297, 800, 297, 800, 297);
            document.getElementById("kloud_selected_text_div").style.display = "none";
            document.getElementById("kloud_result_div").style.display = "";
            document.getElementById("kloud_action_div").style.display = "";
            document.getElementById("kloud_action_replace").classList.add("disabled")
            document.getElementById("kloud_action_insert").classList.add("disabled")
            document.getElementById("kloud_action_try_again").classList.add("disabled")
            document.getElementById("kloud_action_copy").classList.add("disabled")
            document.getElementById("kloud_action_stop").classList.remove("disabled")
        }

        function resizeEndStyle() {
            document.getElementById("kloud_action_replace").classList.remove("disabled")
            document.getElementById("kloud_action_insert").classList.remove("disabled")
            document.getElementById("kloud_action_try_again").classList.remove("disabled")
            document.getElementById("kloud_action_copy").classList.remove("disabled")
            document.getElementById("kloud_action_stop").classList.add("disabled")
        }

        function handleResult(result) {
            document.getElementById("kloud_result").innerHTML = result
            document.getElementById("kloud_input").value = ''
            document.getElementById('kloud_result_div').scroll({
                top: document.getElementById('kloud_result_div').scrollHeight,
                behavior: 'smooth'
            });
        }

        function test() {
            const data = {
                "title": "多模态销售助理解决方案文档",
                "paragraph": [
                    {
                        "title": "1. 什么是多模态销售助理？",
                        "content": "多模态销售助理是基于对客户需求及市场环境的深入分析而开发的智能助手，旨在提高销售团队的效率和客户满意度。其背景在于现代销售过程中信息流通不畅、客户需求难以快速捕捉等问题，通过使用多模态技术整合多种交流方式，实现对客户需求的精准理解和响应。",
                        "level": 1
                    },
                    {
                        "title": "2. 核心功能",
                        "content": "多模态销售助理的核心功能包括销售过程全流程追踪、会议中AI演讲的支持以及会议总结和解决方案的撰写。以下是对这些功能的详细说明：",
                        "level": 1
                    },
                    {
                        "title": "2.1 销售过程全流程追踪",
                        "content": "Konverse的核心功能是实现销售过程的全流程追踪，帮助销售人员实时了解客户的需求变化，提升销售效率。通过数据分析和客户反馈，销售人员可以更精准地制定销售策略，确保客户满意度。 Section 2.1 outlines tracking the entire sales process for Kloud, enhancing efficiency and customer satisfaction through data analysis and feedback.",
                        "level": 2
                    },
                    {
                        "title": "2.2 会议中机器人帮助实现深度交流",
                        "content": "多模态的AI演讲功能可以在会议中实时生成演讲稿，支持多种语言，确保信息的准确传达",
                        "level": 2
                    },
                    {
                        "title": "2.3 会议中AI总结并撰写解决方案",
                        "content": "AI总结功能可以在会议结束后自动生成会议纪要和解决方案，帮助团队快速响应客户需求。",
                        "level": 2
                    },
                    {
                        "title": "3. 销售过程中的痛点",
                        "content": "在多模态销售过程中，用户可能遇到的痛点包括沟通不畅、信息不对称、技术障碍和个性化需求难以满足。",
                        "level": 1
                    },
                    {
                        "title": "4. AI的深度学习能力",
                        "content": "Kloud产品利用高度自适应的AI技术，通过构建知识库和产品功能图谱，使机器人具备专家级的知识。AI知识库允许机器人快速学习并回答复杂问题，而产品功能图谱确保机器人能够理解具体产品的每个功能。此外，AI info-link技术使得机器人能够实时更新知识，提升其应用价值。",
                        "level": 1
                    },
                    {
                        "title": "5. 服务方式",
                        "content": "Kloud提供多种服务方式以支持客户需求：",
                        "level": 1
                    },
                    {
                        "title": "5.1 Kloud服务的多种方式",
                        "content": "包括API集成、SaaS模式以及本地部署等，每种方式都有其独特的优势。",
                        "level": 2
                    },
                    {
                        "title": "5.1.1 KLOUD LiveDoc活文档插件",
                        "content": "Kloud LiveDoc插件支持实时文档共享和交互，帮助团队更好地协作，提高工作效率。",
                        "level": 3
                    },
                    {
                        "title": "5.1.2 Kloud meeting plugin",
                        "content": "Kloud Meeting插件支持全方位的会议功能，确保信息的准确传达和记录。",
                        "level": 3
                    },
                    {
                        "title": "5.1.3 Kloud Konverse智会插件",
                        "content": "Kloud Konverse插件能够实现智能化的会议交流，提高会议的互动性和效率。",
                        "level": 3
                    },
                    {
                        "title": "5.2 Kloud开放API",
                        "content": "Kloud开放API为软件开发行业提供灵活的集成方式，支持客户进行二次开发。",
                        "level": 2
                    },
                    {
                        "title": "5.3 本地部署的服务方式",
                        "content": "本地部署的方式能提供更高的数据安全性和隐私保护，适合对安全性要求较高的企业。",
                        "level": 2
                    },
                    {
                        "title": "5.4 SaaS类型的服务方式",
                        "content": "SaaS类型的服务方式则提供了更高的灵活性，客户可以根据需要随时调整服务内容。",
                        "level": 2
                    },
                    {
                        "title": "6. AI解决方案撰写步骤",
                        "content": "多模态销售助理解决方案的生成步骤包括：生成提纲、活文档内容生成以及AI对内容的自动迭代与更新，每一步都旨在提升销售团队的响应速度和准确性。",
                        "level": 1
                    },
                    {
                        "title": "7. 带给企业的价值",
                        "content": "多模态销售助理为企业带来的价值包括提高客户满意度、增强销售团队的效率以及优化客户互动体验。Kloud根据客户需求提供定制化的服务，确保满足每个客户的特定需求。",
                        "level": 1
                    },

                ]
            };

            insertText(data['title'] + "\n", 60, 1, true)
            var test_loop = 0;
            var test_timer = setInterval(function () {
                if (test_loop > data['paragraph'].length - 2) {
                    clearInterval(test_timer)
                    that.executeCommand('close', '')
                }
                let fontSize = 20
                if (data['paragraph'][test_loop].level === 1) {
                    fontSize = 40
                }
                if (data['paragraph'][test_loop].level === 2) {
                    fontSize = 30
                }
                if (data['paragraph'][test_loop].level === 3) {
                    fontSize = 25
                }
                insertText(data['paragraph'][test_loop].title, fontSize, 2, true)
                // window.Asc.plugin.executeMethod("AddContentControl", [2, { "Id": test_loop, "Tag": "{tag" + test_loop + "}", "Lock": 0 }]);

                insertText(data['paragraph'][test_loop].content, fontSize - 5)
                test_loop++;
            }, 100);

            window.Asc.plugin.executeMethod("MoveCursorToContentControl", [1, false]);
        }
        function insertText(content, fontSize, heading = -1, bold = false) {
            Asc.scope.text = String(content)
            Asc.scope.fontSize = fontSize
            Asc.scope.heading = heading
            Asc.scope.bold = bold
            that.callCommand(function () {
                var oDocument = Api.GetDocument();
                var oParagraph = Api.CreateParagraph();
                var oRun = Api.CreateRun();
                var oNewDocumentStyle = oDocument.GetStyle("Heading " + Asc.scope.heading);

                oParagraph.SetStyle(oNewDocumentStyle);
                oRun.SetFontFamily("WenQuanYi Zen Hei");
                oRun.SetFontSize(Asc.scope.fontSize);
                if (Asc.scope.bold) {
                    oRun.SetBold(true)
                }
                oRun.AddText(Asc.scope.text);
                oParagraph.AddElement(oRun);

                oDocument.InsertContent([oParagraph]);
            }, false);
        }
        async function generateAiWriting() {
            const data = [
                {
                    "title": "多模态销售助理解决方案文档",
                    "content": "多模态销售助理解决方案文档",
                    "level": 0
                },
                {
                    "title": "1. 什么是多模态销售助理？",
                    "content": "多模态销售助理是基于对客户需求及市场环境的深入分析而开发的智能助手，旨在提高销售团队的效率和客户满意度。其背景在于现代销售过程中信息流通不畅、客户需求难以快速捕捉等问题，通过使用多模态技术整合多种交流方式，实现对客户需求的精准理解和响应。",
                    "level": 1
                },
                {
                    "title": "2. 核心功能",
                    "content": "多模态销售助理的核心功能包括销售过程全流程追踪、会议中AI演讲的支持以及会议总结和解决方案的撰写。以下是对这些功能的详细说明：",
                    "level": 1
                },
                {
                    "title": "2.1 销售过程全流程追踪",
                    "content": "Konverse的核心功能是实现销售过程的全流程追踪，帮助销售人员实时了解客户的需求变化，提升销售效率。通过数据分析和客户反馈，销售人员可以更精准地制定销售策略，确保客户满意度。 Section 2.1 outlines tracking the entire sales process for Kloud, enhancing efficiency and customer satisfaction through data analysis and feedback.",
                    "level": 2
                },
                {
                    "title": "2.2 会议中机器人帮助实现深度交流",
                    "content": "多模态的AI演讲功能可以在会议中实时生成演讲稿，支持多种语言，确保信息的准确传达",
                    "level": 2
                },
                {
                    "title": "2.3 会议中AI总结并撰写解决方案",
                    "content": "AI总结功能可以在会议结束后自动生成会议纪要和解决方案，帮助团队快速响应客户需求。",
                    "level": 2
                },
                {
                    "title": "3. 销售过程中的痛点",
                    "content": "在多模态销售过程中，用户可能遇到的痛点包括沟通不畅、信息不对称、技术障碍和个性化需求难以满足。",
                    "level": 1
                },
                {
                    "title": "4. AI的深度学习能力",
                    "content": "Kloud产品利用高度自适应的AI技术，通过构建知识库和产品功能图谱，使机器人具备专家级的知识。AI知识库允许机器人快速学习并回答复杂问题，而产品功能图谱确保机器人能够理解具体产品的每个功能。此外，AI info-link技术使得机器人能够实时更新知识，提升其应用价值。",
                    "level": 1
                },
                {
                    "title": "5. 服务方式",
                    "content": "Kloud提供多种服务方式以支持客户需求：",
                    "level": 1
                },
                {
                    "title": "5.1 Kloud服务的多种方式",
                    "content": "包括API集成、SaaS模式以及本地部署等，每种方式都有其独特的优势。",
                    "level": 2
                },
                {
                    "title": "5.1.1 KLOUD LiveDoc活文档插件",
                    "content": "Kloud LiveDoc插件支持实时文档共享和交互，帮助团队更好地协作，提高工作效率。",
                    "level": 3
                },
                {
                    "title": "5.1.2 Kloud meeting plugin",
                    "content": "Kloud Meeting插件支持全方位的会议功能，确保信息的准确传达和记录。",
                    "level": 3
                },
                {
                    "title": "5.1.3 Kloud Konverse智会插件",
                    "content": "Kloud Konverse插件能够实现智能化的会议交流，提高会议的互动性和效率。",
                    "level": 3
                },
                {
                    "title": "5.2 Kloud开放API",
                    "content": "Kloud开放API为软件开发行业提供灵活的集成方式，支持客户进行二次开发。",
                    "level": 2
                },
                {
                    "title": "5.3 本地部署的服务方式",
                    "content": "本地部署的方式能提供更高的数据安全性和隐私保护，适合对安全性要求较高的企业。",
                    "level": 2
                },
                {
                    "title": "5.4 SaaS类型的服务方式",
                    "content": "SaaS类型的服务方式则提供了更高的灵活性，客户可以根据需要随时调整服务内容。",
                    "level": 2
                },
                {
                    "title": "6. AI解决方案撰写步骤",
                    "content": "多模态销售助理解决方案的生成步骤包括：生成提纲、活文档内容生成以及AI对内容的自动迭代与更新，每一步都旨在提升销售团队的响应速度和准确性。",
                    "level": 1
                },
                {
                    "title": "7. 带给企业的价值",
                    "content": "多模态销售助理为企业带来的价值包括提高客户满意度、增强销售团队的效率以及优化客户互动体验。Kloud根据客户需求提供定制化的服务，确保满足每个客户的特定需求。",
                    "level": 1
                },
            ]
            let index = 0
            const resjson = await fetch('https://officeapi.kloud.cn/files/getAiWritingFileStyle')
            const res = await resjson.json()
            const styleData = JSON.parse(res.data)
            Asc.scope.styleData = styleData
            console.log(styleData);
            const set = new Set()
            for (let key in styleData) {
                if (key.includes('Heading')) {
                    set.add(Number(key[key.length - 1]))
                }
            }
            const max = Math.max(...set)
            Asc.scope.maxHeading = 'Heading ' + max

            that.callCommand(() => {
                var oDocument = Api.GetDocument();
                oDocument.RemoveAllElements();
            }, false)
            const interval = setInterval(() => {
                if (index == data.length) {
                    clearInterval(interval)
                    return
                }
                Asc.scope.section = data[index]
                that.callCommand(() => {
                    var oDocument = Api.GetDocument();
                    var oParagraph = Api.CreateParagraph();
                    oParagraph.AddText(Asc.scope.section.title)
                    var oStyleFromJSON
                    if (Asc.scope.section.level == 0) {
                        oStyleFromJSON = Api.FromJSON(Asc.scope.styleData['Title'].styleJson)
                    } else if (Asc.scope.section.level > 0) {
                        var headingName = 'Heading ' + Asc.scope.section.level
                        oStyleFromJSON = Api.FromJSON(Asc.scope.styleData[headingName]?.styleJson || Asc.scope.styleData[Asc.scope.maxHeading].styleJson)
                    }
                    oParagraph.SetStyle(oStyleFromJSON)
                    oDocument.InsertContent([oParagraph])

                    if (Asc.scope.section.level > 0) {
                        var oParagraph2 = Api.CreateParagraph();
                        oParagraph2.AddText(Asc.scope.section.content)
                        if (Asc.scope.styleData['Normal']) {
                            oStyleFromJSON = Api.FromJSON(Asc.scope.styleData['Normal'].styleJson)
                            oParagraph2.SetStyle(oStyleFromJSON)
                        }
                        oDocument.InsertContent([oParagraph2])
                    }

                }, false);
                index++
            }, 1000)


        }
    };
})(window, undefined);